// compile: g++ -o char_conv char_conv.cc -std=c++17
// run: ./char_conv
#include <array>
#include <charconv>
#include <iomanip>
#include <iostream>
#include <string_view>
#include <system_error>
using namespace std;

void Test1() {
  std::array<char, 10> str;

  if (auto [ptr, ec] = std::to_chars(str.data(), str.data() + str.size(), 42);
      ec == std::errc())
    // C++20, uses string_view(first, last)
    // std::cout << std::string_view(str.data(), ptr);
    // C++17, uses string_view(ptr, length)
    std::cout << (str.data(), ptr - str.data());
}
void Test2() {
  for (std::string_view const str : {"15 foo", "bar", " 42", "5000000000"}) {
    std::cout << "String: " << std::quoted(str) << ". ";

    int result{};

    auto [ptr,
          ec]{std::from_chars(str.data(), str.data() + str.size(), result)};

    if (ec == std::errc()) {
      std::cout << "Result: " << result << ", ptr -> " << std::quoted(ptr)
                << '\n';
    } else if (ec == std::errc::invalid_argument) {
      std::cout << "That isn't a number.\n";
    } else if (ec == std::errc::result_out_of_range) {
      std::cout << "This number is larger than an int.\n";
    }
  }
}
int main() {
  Test1();
  Test2();
  return 0;
}
